package com.zking.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zking.dto.ResultDto;
import com.zking.dto.UserDto;
import com.zking.entity.User;
import com.zking.mapper.IUserMapper;
import com.zking.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.annotation.MultipartConfig;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController @RequiredArgsConstructor
@CrossOrigin // 允许跨域
// @RequestMapping("/api")
public class MyController2 {
    // 如果这里使用了接口，必须使用接口类型作为自动注入的类型
    // 不能使用UserServiceImpl，而是IUserService
    private final UserService userService;
    private final IUserMapper userMapper;
    
    @Value("${server.servlet.context-path}")
    private String contextPath;
    
    /*
    SpringMVC中：将对象转为JSON字符串
    SpringBoot中：直接返回对象（自动转为JSON字符串）
     */
    @GetMapping("/tt1")
    public List<User> tt1() {
        // userService.getAll().forEach(System.out::println);
        return userService.getAll();
        // return "mybatis-plus-666";
    }
    
    @PostMapping("/api/auth/login")
    public ResultDto<User> login(@RequestBody Map<String, Object> map) {
        User user = userMapper.selectOne(new QueryWrapper<User>()
                .eq("username", map.get("name"))
                .eq("password", map.get("password")));
        if (user == null) {
            // return new ResultDto<>(400, "用户名或者密码错误", null);
            return ResultDto.fail(400, "用户名或者密码错误");
        } else {
            // return new ResultDto<>(0, null, data);
            
            Map<String, Object> data = new HashMap<>();
            data.put("token", "123123123123123");
            // return ResultDto.success(data);
            
            // 包含ID/money/token的用户信息
            user.setToken(UUID.randomUUID().toString());
            return ResultDto.success(user);
        }
    }
    
    @PostMapping("/api/auth/login2")
    public ResultDto<UserDto> login(@RequestBody UserDto user) {
        User u = userMapper.selectOne(new QueryWrapper<User>()
                .eq("username", user.getName())
                .eq("password", user.getPassword()));
        if (u == null) {
            return ResultDto.fail(400, "失败");
        }
        UserDto data = new UserDto();
        data.setId(u.getId());
        data.setName(u.getUsername());
        data.setToken("123123123123123");
        return ResultDto.success(data);
    }
    
    // @GetMapping("/api/tt2")
    @RequestMapping("/api/tt2")
    public ResultDto<Page<User>> tt2(int pageNum) {
        return new ResultDto<>(0, null, userService.getPage(2, 3));
        // return userService.getPage(2, 3);
        // return "mybatis-plus-777";
    }
    
    // 返回String作为URL给前端，code\message\data由ResultDto封装
    @Value("${upload.path}")
    private String uploadPath;
    
    @PostMapping("/api/upload")
    public ResultDto<String> upload(@RequestParam("image") MultipartFile file) throws IOException {
        String name = UUID.randomUUID() + "-" + file.getOriginalFilename();
        // String dir = "D:/"; // 被配置替换
        file.transferTo(new File(uploadPath, name));
        // http://localhost:8080/
        return ResultDto.success("/static/" + name);
    }
}
